import React, { useState, useEffect } from 'react';
import styles from '../css/strategy.module.css';
import { useNavigate } from 'react-router-dom';
import { Swiper } from 'antd-mobile';
import leftwhite from '../assets/left.png';
import hourse3 from '../assets/hourse3.png';
import starttwo from '../assets/graystar.png';
import startone from '../assets/redstar.png';
import starthree from '../assets/starthree.png';
import loveImg from '../assets/love.png';
import loveRed from '../assets/love-red.png';
import starr from '../assets/graystar.png';
import starts from '../assets/starts.png';
import commentImg from '../assets/yan.png';
import defaultAvatar from '../assets/pandaback.png';
import browseIcon from '../assets/active.png';
import { getTravelComments, toggleCollection } from '../api/strategys';
import { imgUrl } from '../config'; // 导入imgUrl
const Strategy = () => {
    // 从sessionStorage中获取playid并初始化状态
    const [playid, setPlayid] = useState(sessionStorage.getItem("playid"));
    // 从sessionStorage中获取game并初始化为空对象
    const [game, setGame] = useState(JSON.parse(sessionStorage.getItem("game")) || {});
    // 初始化评论数据状态为空数组
    const [datas, setDatas] = useState([]);
    // 初始化轮播图数据状态为空数组
    const [banner, setBanner] = useState([]);
    // 获取用于导航的navigate函数
    const navigate = useNavigate();

// 修改后的数据获取逻辑
useEffect(() => {
  if (game.id) {
    getTravelComments(game.id)
      .then(res => {
        console.log('评论数据:', res);
        setDatas(res.data || []); // 直接使用 res.data
      })
      .catch(error => {
        console.error('获取评论失败:', error);
      });
  }
}, [game, playid]);

    // 处理图片加载错误，将图片设置为默认头像
    const handleImgError = (e) => {
        e.target.src = defaultAvatar;
    };

    // 处理返回上一页的操作
    const goBack = () => {
        window.history.back();
    };

    // 处理添加评论的操作，设置相关sessionStorage并导航到指定页面
    const goToAddComment = () => {
        sessionStorage.setItem("status", 2);
        sessionStorage.setItem("comentid", game.id);
        navigate("/scenicname");
    };

    // 处理查看评论详情的操作，设置相关sessionStorage并跳转到评论详情页面
    const goToCommentDetail = (i, id, trid) => {
        sessionStorage.setItem("comitem", JSON.stringify(datas[i]));
        sessionStorage.setItem("scenic_ids", game.playid);
        window.location.href = "comtent.html";
    };

    // 处理点赞操作
    const handleLike = () => {
  if (!playid) {
    console.log('请先登录');
    return;
  }
  
  toggleCollection(playid, 3, game.id)
    .then(res => {
      console.log('点赞结果:', res);
      if (res.data === 1) {
        // 点赞成功处理
        document.querySelector(`.${styles['like-success']}`).style.display = 'block';
        setTimeout(() => {
          document.querySelector(`.${styles['like-success']}`).style.display = 'none';
        }, 1000);
        document.getElementById("lover").src = loveRed;
      } else if (res.data === 2) {
        // 取消点赞处理
        document.getElementById("lover").src = loveImg;
        document.querySelector(`.${styles['like-no']}`).style.display = 'block';
        setTimeout(() => {
          document.querySelector(`.${styles['like-no']}`).style.display = 'none';
        }, 1000);
      }
    })
    .catch(error => {
      console.error('点赞失败:', error);
    });
};

    // 处理收藏操作
   const handleCollect = () => {
  if (!playid) {
    console.log('请先登录');
    return;
  }
  
  toggleCollection(playid, 1, game.id)
    .then(res => {
      console.log('收藏结果:', res);
      if (res.data === 1) {
        // 收藏成功处理
        document.getElementById("startImg").src = starts;
        document.querySelector(`.${styles.revamp}`).style.display = 'block';
        setTimeout(() => {
          document.querySelector(`.${styles.revamp}`).style.display = 'none';
        }, 1000);
      } else if (res.data === 2) {
        // 取消收藏处理
        document.getElementById("startImg").src = starr;
        document.querySelector(`.${styles.collect}`).style.display = 'block';
        setTimeout(() => {
          document.querySelector(`.${styles.collect}`).style.display = 'none';
        }, 1000);
      }
    })
    .catch(error => {
      console.error('收藏失败:', error);
    });
};
    // 根据评分渲染星星图标
    const renderStars = (score) => {
        if (score === 1) {
            return (
                <div className={styles.start}>
                    <img src={starttwo} alt="" />
                    <img src={startone} alt="" />
                    <img src={startone} alt="" />
                    <img src={startone} alt="" />
                    <img src={startone} alt="" />
                </div>
            );
        } else if (score === 1.5) {
            return (
                <div className={styles.start}>
                    <img src={starttwo} alt="" />
                    <img src={starthree} alt="" />
                    <img src={startone} alt="" />
                    <img src={startone} alt="" />
                    <img src={startone} alt="" />
                </div>
            );
        } else if (score === 2) {
            return (
                <div className={styles.start}>
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={startone} alt="" />
                    <img src={startone} alt="" />
                    <img src={startone} alt="" />
                </div>
            );
        } else if (score === 2.5) {
            return (
                <div className={styles.start}>
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={starthree} alt="" />
                    <img src={startone} alt="" />
                    <img src={startone} alt="" />
                </div>
            );
        } else if (score === 3) {
            return (
                <div className={styles.start}>
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={startone} alt="" />
                    <img src={startone} alt="" />
                </div>
            );
        } else if (score === 3.5) {
            return (
                <div className={styles.start}>
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={starthree} alt="" />
                    <img src={startone} alt="" />
                </div>
            );
        } else if (score === 4) {
            return (
                <div className={styles.start}>
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={startone} alt="" />
                </div>
            );
        } else if (score === 4.5) {
            return (
                <div className={styles.start}>
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={starthree} alt="" />
                </div>
            );
        } else if (score === 5) {
            return (
                <div className={styles.start}>
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                    <img src={starttwo} alt="" />
                </div>
            );
        }
        // 默认返回5星
        return (
            <div className={styles.start}>
                <img src={starttwo} alt="" />
                <img src={starttwo} alt="" />
                <img src={starttwo} alt="" />
                <img src={starttwo} alt="" />
                <img src={starttwo} alt="" />
            </div>
        );
    };

    return (
        <div style={{ backgroundColor: '#ffffff' }}>
            {/* 收藏成功提示 */}
            <div className={styles.revamp}>
                <div className={styles.revamps}>
                    <div className={styles['revamp-one']}>收藏成功！</div>
                </div>
            </div>
            {/* 取消收藏提示 */}
            <div className={styles.collect}>
                <div className={styles.collects}>
                    <div className={styles['collect-one']}>已取消收藏！</div>
                </div>
            </div>
            {/* 点赞成功提示 */}
            <div className={styles['like-success']}>
                <div className={styles.like}>
                    <div className={styles['like-one']}>已点赞！</div>
                </div>
            </div>
            {/* 取消点赞提示 */}
            <div className={styles['like-no']}>
                <div className={styles.nolike}>
                    <div className={styles['nolike-one']}>已取消！</div>
                </div>
            </div>

            <div className={styles.big}>
                {/* 顶部导航栏 */}
                <div className={styles.top}>
                    <div className={styles.left} onClick={goBack}>
                        <img src={leftwhite} alt="" />
                    </div>

                    {/* 轮播图区域 */}
                    <div className="plug_slider">
                        <Swiper
                            autoplay={true}
                            loop
                            onIndexChange={(index) => console.log('slide to', index)}
                        >
                            {banner && banner.length > 0 ? (
                                banner.map((item, index) => (
                                    <Swiper.Item key={index}>
                                        <div style={{ width: '100%', height: '300px' }}>
                                            <img 
                                                src={item ? `${imgUrl}${item}` : defaultAvatar} 
                                                alt={`轮播图${index + 1}`} 
                                                onError={handleImgError}
                                                style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                                            />
                                        </div>
                                    </Swiper.Item>
                                ))
                            ) : (
                                <Swiper.Item>
                                    <div style={{ width: '100%', height: '300px' }}>
                                        <img src={defaultAvatar} alt="暂无图片" onError={handleImgError} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                                    </div>
                                </Swiper.Item>
                            )}
                        </Swiper>
                    </div>
                </div>

                {/* 标题 */}
                <h3 id="two" style={{ marginLeft: '10px', marginTop: '5px', display: 'block' }}>
                    {game.title || '熊猫"双""娇"入住五龙山'}
                </h3>

                {/* 作者信息区域 */}
                <div className={styles.imager}>
                    <img
                        id="headImg"
                        src={game.avatar ? `${imgUrl}${game.avatar}` : defaultAvatar}
                        alt=""
                        onError={handleImgError}
                    />
                    <span
                        id="title"
                        style={{ textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}
                    >
                        {game.name || '旅游达人'}
                    </span>
                    <span id="date">
                        {game.create_time ? game.create_time.split(' ')[0] : '2023-05-01'}
                    </span>
                </div>

                {/* 内容区域 */}
                <div className={styles['content-font']}>
                    <span id="introduce">{game.content || '五龙山动物园的熊猫好可爱！下次还来这里'}</span>
                </div>

                {/* 评论标题区域 */}
                <div className={styles.comment}>
                    <h3>评论</h3>
                    <span style={{ marginRight: '15px' }}>
                        全部 <span id="even">{datas.length || 0}</span> 条
                    </span>
                </div>

                {/* 评论列表区域 */}
                <div className={styles['big-comment']}>
                    {datas && datas.length === 0 ? (
                        <p id="none">暂无评论...</p>
                    ) : (
                        datas.map((item, i) => (
                            <div
                                key={i}
                                className={styles['comment-item']}
                                onClick={() => goToCommentDetail(i, item.id, item.intri_id)}
                            >
                                <div className={styles.coment}>
                                    <img
                                        src={item.avatar ? `${imgUrl}${item.avatar}` : defaultAvatar}
                                        alt=""
                                        onError={handleImgError}
                                    />
                                    <div style={{ width: '100%' }}>
                                        <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                                            <span>{item.name}</span>
                                            <span style={{ marginRight: '20px' }}>{item.create_time}</span>
                                        </div>
                                        <div style={{ display: 'flex', alignItems: 'center' }}>
                                            <p>评分</p>
                                            {renderStars(item.score)}
                                        </div>
                                    </div>
                                </div>

                                <div className={styles['content-font']}>
                                    <span>{item.content}</span>
                                </div>

                                <div
                                    className={styles['comment-img']}
                                    onClick={() => goToCommentDetail(i, item.id, item.intri_id)}
                                >
                                    <img
                                        src={item.img ? `${imgUrl}${item.img}` : defaultAvatar}
                                        alt=""
                                        onError={handleImgError}
                                    />
                                </div>

                                <div className={styles.browse}>
                                    <span>浏览{item.number || 0}</span>
                                    <img src={browseIcon} alt="" />
                                </div>
                            </div>
                        ))
                    )}
                </div>

                {/* 底部导航栏 */}
                <div className={styles.bottom}>
                    <div className={styles.add} onClick={goToAddComment}>添加评论...</div>
                    <div className={styles.threeBlock}>
                        <div className={styles.love}>
                            <img id="lover" onClick={handleLike} src={loveImg} alt="" />
                            <span id="love-like">{game.like_num || 0}</span>
                        </div>
                        <div className={styles.love}>
                            <img id="startImg" onClick={handleCollect} src={starr} alt="" />
                            <span id="collect_num">{game.collect_num || 0}</span>
                        </div>
                        <div className={styles.love}>
                            <img src={commentImg} alt="" />
                            <span id="nine">{datas ? datas.length : 0}</span> 
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Strategy;